use "Data/cleaned_data/Master.dta", clear

destring year, replace
encode country, gen(country_id)
xtset country_id year

*setting structural break (before and after exit from bond market)
/*
gen country_broken = country
local countries_broken "Ireland" "Greece" "Cyprus" "Portugal"
foreach c of local countries_broken {
    if bondMarketAbsence == 1{
		replace country_broken = "`country'_absence"
	}
	if
    
    * Only proceed if such rows exist
    if r(N) > 0 {
        * Get first and last year where bondMarketAbsence == 1
        quietly summarize year if country == "`c'" & bondMarketAbsence == 1, meanonly
        local first_year = r(min)
        local last_year  = r(max)

        * Update country_broken for rows before and after the absence period
        replace country_broken = "`c'_pre"  if country == "`c'" & year < `first_year'
        replace country_broken = "`c'_post" if country == "`c'" & year > `last_year'
    }
}
*/

//Debt Year 0
bysort country (year): gen debtYear0 = debt if !missing(debt) & _n == 1
bysort country (year): replace debtYear0 = debtYear0[_n-1] if missing(debtYear0)

//rho: Recovery Rate
*assistance amount as a percentage of defaulted debt
	*consolidating defaultAmount as the amount of debt during the first assistance period
gen defaultAmount = debt if country == "Ireland" & year==2011
replace defaultAmount = debt if country == "Greece" & year==2010
replace defaultAmount = debt if country == "Spain" & year==2012
replace defaultAmount = debt if country == "Cyprus" & year==2013
replace defaultAmount = debt if country == "Portugal" & year==2011
gen recoveryRate = assistanceAmountTotal / defaultAmount
drop assistanceAmountTotal
	*filling up and down
gen recoveryRate_first = .
bysort country (year): replace recoveryRate_first = recoveryRate if assistanceYear == 1
bysort country (recoveryRate_first year): replace recoveryRate_first = recoveryRate_first[_n-1] if missing(recoveryRate_first)
bysort country (year): replace recoveryRate_first = recoveryRate_first[_n-1] if missing(recoveryRate_first)
gsort country -year
bysort country (year): replace recoveryRate_first = recoveryRate_first[_n-1] if missing(recoveryRate_first)
replace recoveryRate = recoveryRate_first
drop recoveryRate_first
sort country year
	*because spain's recovery rate is incredibly low, at 4.45%, this shows that the assistance package was likely not for defaulted debt, but precautionary assistance. I exclude spain's recovery rate with this reasoning. 
replace recoveryRate = . if country == "Spain" 
*bysort country (year): ipolate recoveryRate year, gen(recoveryRate_i) epolate
*drop defaultAmount recoveryRate
*rename recoveryRate_i recoveryRate
drop defaultAmount
replace recoveryRate = 1 if missing(recoveryRate)

save "Data/cleaned_data/Master_1.dta", replace
use "Data/cleaned_data/Master_1.dta", clear
//Preping for Main
gen phi = 0
gen w = 0
gen tax = 0

bysort country: gen year_count = _n
xtset country_id year
gen base = ((sInterestRateAvgAnnual)*L1.debt + expenditure-revenue-assistanceAmount-covidAssistanceAmount)
gen prod = .
gen row_number = _n
gen baseProd =.
gen phiProd=.
gen phiPhiProd =.

	*fixing w_EU
bysort year: egen w_EU = total(w)
bysort year: egen EUgdp = total (gdp)
bysort year: egen EUdebt = total (debt)
	//country deficit threshold
xtset country_id year
gen gdpGrowthRate = (gdp - L1.gdp) / L1.gdp
gen sDeficitPercentage = (sInterestRateAvgAnnual-gdpGrowthRate)/(1+gdpGrowthRate)*L1.debt/gdp
	*254/491 obs being negative, meaning improved debt situation from previous year
	*145/491 obs being larger than 0.03, meaning tax should apply
count
count if sDeficitPercentage < 0
count if sDeficitPercentage >= 0.03
gen sDeficitConstraint = sDeficitPercentage >= 0.03
	//country debt level threshold
gen sDebtLevelPercentage = w/gdp
gen sDebtLevelConstraint = sDebtLevelPercentage>=0.6
	//EU deficit threshold
xtset country_id year
gen EUgdpGrowthRate = (EUgdp - L1.EUgdp) / L1.EUgdp
gen EUDeficitPercentage = (euInterestRateAvgAnnual-EUgdpGrowthRate)/(1+EUgdpGrowthRate)*L1.EUdebt/EUgdp
gen EUDeficitConstraint = EUDeficitPercentage>=0.03
	//EU debt level threshold is built within the loop
gen EUDebtLevelPercentage = .
gen EUDebtLevelConstraint = .
	*setting beta ratios
gen beta_0 = 0.3
gen beta_1 = beta_0 * beta_0
gen beta_2 = beta_0 * (1 - beta_0)
gen beta_3 = (1 - beta_0) * beta_0
gen beta_4 = (1 - beta_0) * (1 - beta_0)
gen beta_5 = beta_0
gen beta_6 = 1 - beta_0
save "Data/cleaned_data/Analysis_1.dta", replace
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
use "Data/cleaned_data/Analysis_1.dta", clear
//Main==========================================================================
forvalues i = 1/10 {
	
//phi==========================
xtset country_id year
	*(minus tax because it's a negative number)
replace phi = (F1.debt / (1+euInterestRateAvgAnnual) - tax) *defaultRateAvgAnnual /(1+euInterestRateAvgAnnual+defaultRateAvgAnnual)
	*experimental phi: 
*replace phi = (F1.debt / (1+euInterestRateAvgAnnual) - tax)*defaultRateAvgAnnual /(1+euInterestRateAvgAnnual+defaultRateAvgAnnual)

	*Moving Window of phiFour-----------
{
local year_count_max = _N
xtset country_id year
	*Get a list of unique countries
levelsof country, local(countries) 
local phiprodListFinal
foreach c of local countries {
    *Create an empty local macro for each country's list
    local rates_`c'
    *Loop through the dataset and collect rates for this country
    quietly {
        forvalues i = 1/`=_N' {
            if country[`i'] == "`c'" {
                local rates_`c' `rates_`c'' `=sInterestRateAvgAnnual[`i']'
            }
        }
    }
	*display the collected list for each country
    *di "Interest rates for `c': `rates_`c''"
	*Create an empty local macro for each country's list
    local growthRates_`c'
    *Loop through the dataset and collect rates for this country
    quietly {
        forvalues i = 1/`=_N' {
            if country[`i'] == "`c'" {
                local growthRates_`c' `growthRates_`c'' `=gdpGrowthRate[`i']'
            }
        }
    }
	*display the collected list for each country
    *di "Interest rates for `c': `rates_`c''"
	*
	su year_count if country == "`c'", meanonly
    *store the maximum value of year_count in a local macro
    local max_year_count = r(max)
	*di "`max_year_count'"
	local phiprodList
	forvalues i = 1/`max_year_count' {	
		local current_year_count = year_count[`i']
		*di "For country `c' row `i', the current_year_count value is `current_year_count'"
		local phiprod=1
		local start = cond(`current_year_count' - 4 < 1, 1, `current_year_count' - 4)
		if `current_year_count'>1 {
			forvalues j=`start'/`current_year_count' {
			*forvalues j=3/`current_year_count' {
			*di "year `j' for `c':"
			local tempRate = real(word("`rates_`c''", `j'))
			*di "`tempRate'"
			local tempGrowthRate = real(word("`growthRates_`c''", `j'))
			local phiprod =`phiprod'*(1+`tempRate')/(1+`tempGrowthRate')
			*di "`phiprod'"
			}
		}
		*di "`phiprod'"
		local phiprodList `phiprodList' `phiprod'	
	}
	local phiprodListCount = wordcount("`phiprodList'")
	*di "for country `c': Current phiprodList: `phiprodList' | Count of phiprodList: `phiprodListCount'"
	local phiprodListFinal `phiprodListFinal' `phiprodList'
}

forvalues i = 1/`=_N' {
	replace phiProd = real(word("`phiprodListFinal'", `i')) if row_number == `i'
}
*!!! although negligible difference, still problematic procedure: an omittance of intial 4-years' of philprod
replace phiProd =1 if phiProd==. & year !=2025
replace phiPhiProd = phi * phiProd
	*phiFour
levelsof country, local(countries)
xtset country_id year
gen phiPhiProd_L1 = L1.phiPhiProd
gen phiPhiProd_L2 = L2.phiPhiProd
gen phiPhiProd_L3 = L3.phiPhiProd
gen phiPhiProd_L4 = L4.phiPhiProd
egen phiFour = rowtotal(phiPhiProd_L4 phiPhiProd_L3 phiPhiProd_L2 phiPhiProd_L1 phiPhiProd)
replace phiFour = phiFour
drop phiPhiProd_L1 phiPhiProd_L2 phiPhiProd_L3 phiPhiProd_L4
}
	
//w============================
local year_count_max = _N
xtset country_id year
replace w=debtYear0 if year_count==1
	*Get a list of unique countries
levelsof country, local(countries) 
local prodListFinal
foreach c of local countries {
    *Create an empty local macro for each country's list
    local rates_`c'
    *Loop through the dataset and collect rates for this country
    quietly {
        forvalues i = 1/`=_N' {
            if country[`i'] == "`c'" {
                local rates_`c' `rates_`c'' `=sInterestRateAvgAnnual[`i']'
            }
        }
    }
	*display the collected list for each country
    *di "Interest rates for `c': `rates_`c''"
	*Create an empty local macro for each country's list
    local growthRates_`c'
    *Loop through the dataset and collect rates for this country
    quietly {
        forvalues i = 1/`=_N' {
            if country[`i'] == "`c'" {
                local growthRates_`c' `growthRates_`c'' `=gdpGrowthRate[`i']'
            }
        }
    }
	*display the collected list for each country
    *di "Interest rates for `c': `rates_`c''"
	*
	su year_count if country == "`c'", meanonly
    *store the maximum value of year_count in a local macro
    local max_year_count = r(max)
	*di "`max_year_count'"
	local prodList
	forvalues i = 1/`max_year_count' {	
		local current_year_count = year_count[`i']
		*di "For country `c' row `i', the current_year_count value is `current_year_count'"
		local prod=1
		if `current_year_count'>2 {
			forvalues j=3/`current_year_count' {
				*di "year `j' for `c':"
				local tempRate = real(word("`rates_`c''", `j'))
				*di "`tempRate'"
				local tempGrowthRate = real(word("`growthRates_`c''", `j'))
				local prod =`prod'*(1+`tempRate')/(1+`tempGrowthRate')
				*di "`prod'"
			}
		}
		/*
		else {
			di "pass"
		}
		*/
		*di "`prod'"
		local prodList `prodList' `prod'	
	}
	local prodListCount = wordcount("`prodList'")
	*di "for country `c': Current prodList: `prodList' | Count of prodList: `prodListCount'"
	local prodListFinal `prodListFinal' `prodList'
}
*local prodListFinalCount = wordcount("`prodListFinal'")
*di "Current prodListFinal: `prodListFinal' | Count of prodListFinal: `prodListFinalCount'"
*di "Current prodListFinal: `prodListFinal'"
	*mapping local prodListFinal onto a variable

forvalues i = 1/`=_N' {
	replace prod = real(word("`prodListFinal'", `i')) if row_number == `i'
}
replace baseProd = (base) * prod
*drop basePhi
levelsof country, local(countries)
foreach c of local countries {
	*the financial distress cost is almost as high as debt for France, Italy, and Spain
	*perhaps it shouldn't roll over year to year
    replace w = L1.w + baseProd + (phiFour - L1.phiFour) if country == "`c'" & year_count > 1
}
drop phiFour	
	
	//tao=======================
	*tao proper
bysort year: egen total_w = total(w)
replace w_EU = total_w
drop total_w
sort country year
replace EUDebtLevelPercentage = w_EU/EUgdp
replace EUDebtLevelConstraint = EUDebtLevelPercentage>=0.6
replace tax = - w*recoveryRate*defaultRateAvgAnnual*(sDeficitConstraint * beta_0+sDebtLevelConstraint * (1-beta_0))
if sDebtLevelConstraint==1 {
	replace tax = tax+ (0.6*gdp-w)*(sDeficitConstraint * beta_1+sDebtLevelConstraint * beta_2 + EUDeficitConstraint * beta_3+EUDebtLevelConstraint * beta_4)
}
if sDeficitConstraint==0 & sDebtLevelConstraint==0 &EUDebtLevelConstraint==1{
	replace tax = tax+ (w/w_EU)*(0.6*EUgdp-EUdebt)*(EUDeficitConstraint * beta_5+EUDebtLevelConstraint * beta_6)
}

}
save "Data/cleaned_data/Analysis_2.dta", replace
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

//Maixmization Problem
	//r to g ratio
use "Data/cleaned_data/Analysis_2.dta", clear
destring year, replace
	*gdpGrowthRateThreeYearForward
xtset country_id year
gen pCounter = 0
gen gdpGrowthRateThreeYearForward = 0
replace gdpGrowthRateThreeYearForward = gdpGrowthRate if gdpGrowthRate > 0
replace pCounter = pCounter + 1 if gdpGrowthRate > 0
replace gdpGrowthRateThreeYearForward = gdpGrowthRateThreeYearForward + F1.gdpGrowthRate if (F1.gdpGrowthRate > 0) & !missing(F1.gdpGrowthRate) 
replace pCounter = pCounter + 1 if (F1.gdpGrowthRate > 0) & !missing(F1.gdpGrowthRate) 
replace gdpGrowthRateThreeYearForward = gdpGrowthRateThreeYearForward + F2.gdpGrowthRate if (F2.gdpGrowthRate > 0) & !missing(F2.gdpGrowthRate) 
replace pCounter = pCounter + 1 if (F2.gdpGrowthRate > 0) & !missing(F2.gdpGrowthRate) 
replace gdpGrowthRateThreeYearForward = gdpGrowthRateThreeYearForward/pCounter
	*sInterestRateAvgAnnual3yrForward
sort country year
xtset country_id year
gen sCounter = 0
gen sInterestRateAvgAnnual3yrForward = 0
replace sInterestRateAvgAnnual3yrForward = sInterestRateAvgAnnual
replace sCounter = sCounter + 1
replace sInterestRateAvgAnnual3yrForward = sInterestRateAvgAnnual + F1.sInterestRateAvgAnnual if !missing(F1.sInterestRateAvgAnnual) 
replace sCounter = sCounter + 1 if !missing(F1.sInterestRateAvgAnnual) 
replace sInterestRateAvgAnnual3yrForward = sInterestRateAvgAnnual + F2.sInterestRateAvgAnnual if !missing(F2.sInterestRateAvgAnnual) 
replace sCounter = sCounter + 1 if !missing(F2.sInterestRateAvgAnnual) 
replace sInterestRateAvgAnnual3yrForward = sInterestRateAvgAnnual3yrForward/sCounter
	*ratio
gen rgRatioThreeYearForward = sInterestRateAvgAnnual3yrForward/gdpGrowthRateThreeYearForward
gen rgRatio = sInterestRateAvgAnnual / gdpGrowthRate
	
	//z: debt trap threshold
	//choosing a z: (R*Bt-1)/y  using all EU member states data
summarize rgRatioThreeYearForward, detail
	*financial assistance years happen 11 out of 442 since 1999
count if assistanceYear == 1 
	*assuming 2.5% of the time, a country defaults; z is cut off at 2.3563061
_pctile rgRatioThreeYearForward, p(97.5)
display r(r1)
	*assuming 5% of the time, a country defaults; z is cut off at 1.5841026
_pctile rgRatioThreeYearForward, p(95)
display r(r1)
gen z = 0 if rgRatioThreeYearForward > 2.3563061
replace z = 1 if z==.
sort country year
	//main
gen expectedU = w*z - tax
replace expectedU = 0 if assistanceYear ==1

save "Data/cleaned_data/Analysis_3.dta", replace
